package com.blb.exam.student.filter;

import com.blb.common.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户登录验证过滤器
 */
//@WebFilter({"/*"})
public class UserLoginFilter implements Filter {

    //白名单
    public static final String[] WHITE_LIST = {"user.do","login.jsp","code.do"};

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String url = request.getRequestURL().toString();
        //放行白名单的URL
        for(String whiteUrl : WHITE_LIST){
            //当前URL以白名单的url结尾
            if(url.endsWith(whiteUrl)){
                filterChain.doFilter(request,response);
                return;
            }
        }
        //判断当前请求是否登录过
        User user = (User) request.getSession().getAttribute("user");
        //未登录需要强制跳转登录页面
        if(user == null){
            response.sendRedirect("/student/login.jsp");
            return;
        }
        //正常请求放行
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
}
